package com.hellogwt.client.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.hellogwt.client.event.EditGreetingEvent;
import com.hellogwt.client.service.GreetingServiceAsync;
import com.hellogwt.shared.domain.Greeting;

import java.util.List;

public class GreetingsPresenter implements Presenter {

    public interface Display {
        HasClickHandlers getEditButton();

        void setData(List<Greeting> data);

        Widget asWidget();
    }

    private GreetingServiceAsync greetingService = null;
    private HandlerManager eventBus = null;
    private Display display = null;

    public GreetingsPresenter(GreetingServiceAsync greetingService, HandlerManager eventBus, Display view) {
        this.greetingService = greetingService;
        this.eventBus = eventBus;
        this.display = view;

        bind();
    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());

        fetchData();
    }

    private void bind() {
        display.getEditButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                eventBus.fireEvent(new EditGreetingEvent());
            }
        });
    }

    private void fetchData() {
        greetingService.getGreetings(new AsyncCallback<List<Greeting>>() {
            @Override
            public void onFailure(Throwable throwable) {
                Window.alert("ERROR: Cannot load greetings!");
            }

            @Override
            public void onSuccess(List<Greeting> greetings) {
                display.setData(greetings);
            }
        });
    }
}